package com.live.stamp.base.utils;

import com.live.stamp.web.sms.service.SmsService;
import com.live.stamp.web.sms.service.model.SmsModel;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 验证码工具类
 * @author cwd E-mail: wendong.cao@jsxfedu.com
 * @version 1
 * @date 2018/4/12 16:37
 */
@Component
public class VerCodeUtils {

    private static SmsService smsService;

    public static Map<String, SmsModel> verCodeMap = new HashMap<>();

    public static void delVerCode(String phone) {
        verCodeMap.remove(phone);
    }

    public static String sendVerCode(SmsModel smsModel) {
        String verCode = RandomStringUtils.randomNumeric(4);
        smsModel.setVerCode(verCode);
        smsModel.setSendTime(new Date());

        smsService.sendMessage(smsModel);
        verCodeMap.put(smsModel.getPhone(), smsModel);

        return verCode;
    }

    public static SmsModel getVerCode(String phone) {
        return verCodeMap.get(phone);
    }

    /**
     * 验证验证码
     * @param phone
     * @return
     */
    public static boolean checkVerCode(String phone, String verCode) {
        SmsModel smsModel = getVerCode(phone);
        if(smsModel == null) {
            return false;
        }

        if(StringUtils.equals(verCode, smsModel.getVerCode())) {
            Date sendTime = smsModel.getSendTime();         //发送时间
            Date now = new Date();                          //当前时间
            long diff = now.getTime() - sendTime.getTime();

            if(diff/(1000*60) < 20) {                       //手机验证码20分钟有效
                return true;
            }

            delVerCode(smsModel.getPhone());                //删除验证码
        }

        return false;
    }

    @Autowired
    public void setDatastore(SmsService smsService) {
        VerCodeUtils.smsService = smsService;
    }
}
